package com.community.common.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.community.common.mapper.CommunityMapper;
import com.community.common.mapper.OwnerFriendMapper;
import com.community.common.mapper.PublicUserMapper;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.domain.Community;
import com.community.common.pojo.domain.ManagerUser;
import com.community.common.pojo.domain.PublicUser;
import com.community.common.pojo.dto.ManageUserCondition;
import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.LayuiPage;
import com.community.common.pojo.response.MyResponse;
import com.community.common.pojo.vo.ManagerUserVo;
import com.community.common.service.ManagerUserService;
import com.community.common.util.RSAUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 小区管理员表 前端控制器
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@Controller
@RequestMapping("/user")
public class ManagerUserController {

    @Resource
    private ManagerUserService managerUserService;
    @Resource
    private OwnerFriendMapper ownerFriendMapper;
    @Resource
    private PublicUserMapper publicUserMapper;
    @Resource
    private CommunityMapper communityMapper;

    @ResponseBody
    @PostMapping("/login")
    public MyResponse login(@RequestBody ManagerUser login, HttpServletRequest request, HttpSession session, ModelMap map) {
        String userName = login.getUserName();
        String pwd = RSAUtil.decryptByPrivate(login.getPassword());
        LambdaQueryWrapper<ManagerUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManagerUser::getUserName, userName);
        ManagerUser one = managerUserService.getOne(wrapper);
        if (one != null) {
            if (one.getPassword().equals(pwd)) {
                Community community = communityMapper.selectById(one.getCommunityId());
                UsernamePasswordToken token = new UsernamePasswordToken(userName, pwd);
                SecurityUtils.getSubject().login(token);
                session.setAttribute("userName", userName);
                session.setAttribute("loginUser", one);
                session.setAttribute("role", String.valueOf(one.getRole()));
                session.setAttribute("communityId", one.getCommunityId());
                session.setAttribute("communityName", community!=null? community.getName():"");
                return MyResponse.success();
            }
        }
        return MyResponse.fail();
    }

    /**
     * 登出
     */
    @ResponseBody
    @GetMapping("/logout")
    public void loginOut(HttpSession session) {
        SecurityUtils.getSubject().logout();
    }

    @ResponseBody
    @PostMapping("/add")
    public MyResponse add(ManagerUser managerUser) {
        return managerUserService.add(managerUser);
    }

    @ResponseBody
    @PostMapping("/queryByPage")
    public LayuiPage queryByPage(@RequestBody PageRequest<ManageUserCondition> manageUserConditionPageRequest) {
        List<ManagerUserVo> managerUsersList = managerUserService.queryByPage(manageUserConditionPageRequest);
        return LayuiPage.parsePage(managerUsersList);
    }

    @ResponseBody
    @PostMapping("/delete")
    public MyResponse delete(@RequestBody List<Long> ids) {
        boolean delete = managerUserService.delete(ids);
        if (delete) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    @ResponseBody
    @PostMapping("/edit")
    public MyResponse edit(ManagerUser managerUser) {
        boolean edit = managerUserService.edit(managerUser);
        if (edit) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    @GetMapping("editPage")
    public String editPage(Long id, ModelMap map) {
        ManagerUser managerUser = managerUserService.getById(id);
        map.put("managerUser", managerUser);
        return "manage/accountManage_edit";
    }

    @GetMapping("bindToWxPage")
    public String bindToWxPage(Long id, ModelMap map) {
        ManagerUser managerUser = managerUserService.getById(id);
        map.put("managerUser", managerUser);
        return "manage/accountManage_bindWx";
    }


    @GetMapping("/cameraPermissionPage")
    public String cameraPermissionPage(String openId, ModelMap map) {
        map.put("openId", openId);
        return "manage/publicUserList_cameraPermission";
    }

    /**
     * 给用户设置相机权限
     * userType 0-public_user用户 1-owner_friend用户
     * timeType 0-不允许 1-1天 2-1月 3-半年 4-1年 5-10年
     */
    @ResponseBody
    @GetMapping("cameraAuth/{id}/{communityId}/{userType}/{timeType}")
    public MyResponse cameraAuth(@PathVariable String id, @PathVariable Integer userType,
                                 @PathVariable String timeType, @PathVariable String communityId) {
        if (id == null || userType == null || timeType == null) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        return managerUserService.cameraAuthorization(id, userType, timeType, communityId);
    }

    /**
     * 审核公众号用户信息 1-通过 2-不通过
     */
    @ResponseBody
    @GetMapping("identityAuth/{id}/{type}")
    public MyResponse identityAuth(@PathVariable Integer type, @PathVariable String id) {
        if (id == null || type == null) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        return managerUserService.identityAuth(id, type);
    }

    @GetMapping("/friendNumberPage")
    public String friendNumberPage(String openId, ModelMap map) {
        LambdaQueryWrapper<PublicUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PublicUser::getOpenId,openId);
        PublicUser publicUser = publicUserMapper.selectOne(queryWrapper);
        map.put("publicUser", publicUser);
        return "manage/publicUserList_friendNumber";
    }

    /**
     * 设置用户可以添加的好友数量
     */
    @ResponseBody
    @PostMapping("friendNumber")
    public MyResponse setFriendNumber(PublicUser publicUser) {
        publicUserMapper.updateById(publicUser);
        return MyResponse.success();
    }

}
